const app = getApp();
Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    hidden: true,
    action: null,
    tmp_users: [],
  },
  onLoad(options) {
    console.log(options)
    let users = wx.getStorageSync('users');
    this.setData({
      users: users,
      list: users,
    }, function() {
      if (options.action) {
        this.setData({
          action: options.action
        });
      }
      if (options.tmp_users) {
        let tmp_users = options.tmp_users.split(',');
        if (tmp_users.length) {
          let user_names = [];
          for (let i = 0; i < users.length; i++) {
            if (tmp_users.indexOf(users[i].user_id) != -1) {
              user_names.push(users[i].name);
              users[i].checked = true;
            }
          }
          this.setData({
            users: users,
            list: users,
          })
        }
        this.setData({
          tmp_users: tmp_users,
        })
      }
    })

  },
  onReady() {
    let that = this;
  },
  Search(e) {
    var key_word = e.detail.value;
    let users = this.data.users;
    let list = [];
    for (let i = 0; i < users.length; i++) {
      if (users[i].name.indexOf(key_word) != -1) {
        list.push(users[i]);
      }
    }
    this.setData({
      list: list,
    })
  },
  Select(e) {
    let id = e.currentTarget.id;
    if (!this.data.action) {
      let users = this.data.users;
      let list = this.data.list;
      let tmp_users = this.data.tmp_users;
      let check = null;
      for (let i = 0; i < users.length; i++) {
        if (users[i].user_id == id) {
          check = users[i].checked;
          break;
        }
      }

      for (let i = 0; i < users.length; i++) {
        if (users[i].user_id == id) {
          users[i].checked = !check;
          break;
        }
      }
      for (let i = 0; i < list.length; i++) {
        if (list[i].user_id == id) {
          list[i].checked = !check;
          break;
        }
      }
      let index = tmp_users.indexOf(id)
      if (index != -1) {
        tmp_users.splice(index, 1);
      } else {
        tmp_users.push(id);
      }
      this.setData({
        users: users,
        list: list,
        tmp_users: tmp_users,
      })
      return;
    }
  },
  SelectComplete() {
    let tmp_users = this.data.tmp_users;
    if (!tmp_users.length) {
      wx.showToast({
        title: '请选择至少一个',
        icon: 'none',
      })
      return;
    }
    wx.setStorageSync('tmp_users', this.data.tmp_users);
    wx.navigateBack({
      delta: 1
    })
  },
});